package com.ydm.restaurant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ydm.restaurant.common.constant.UserConstant;
import com.ydm.restaurant.common.exception.BaseException;
import com.ydm.restaurant.mapper.UserMapper;
import com.ydm.restaurant.pojo.entity.User;
import com.ydm.restaurant.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
* @author Liubuzhu
* @description 针对表【user(用户表，用于存储用户的基本信息)】的数据库操作Service实现
* @createDate 2024-12-24 10:49:59
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

	@Autowired
	private UserMapper userMapper;

	public void register(User user) {

		String username = user.getUsername();
		String password = user.getPassword();

		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", username);

		User userTemp = userMapper.selectOne(queryWrapper);   //查询数据库里值等于username的数据
		if (userTemp != null) {
			throw new BaseException(UserConstant.ALREADY_EXISTS);
		}

		QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
		queryWrapper1.orderByDesc("id").last("limit 1");    // 降序选第一个
		User last_user = userMapper.selectOne(queryWrapper1);
		int new_user_uid;
		if (last_user == null) {
			new_user_uid = 1;
		} else {
			new_user_uid = last_user.getId()+ 1;
		}

		//对前端传过来的明文密码进行md5加密处理
		password = DigestUtils.md5DigestAsHex(password.getBytes());

		User registerUser = new User();
		//对象属性拷贝
		BeanUtils.copyProperties(user, registerUser);

		//设置当前记录创建时间
		registerUser.setPassword(password);

		//设置默认的信息
		registerUser.setNickname("用户_" + new_user_uid);
		registerUser.setPhone("");
		registerUser.setImage("https://my-flower-lhh.oss-cn-chengdu.aliyuncs.com/avatar/dcd128cd0205338d1bbd186b970b8214.jpg");

		userMapper.insert(registerUser);
	}

}




